<template>
  <div v-if="plainOptions.length" class="flex justify-between pt-2 items-center">
    <div>
      <Checkbox
        v-model:checked="checkAll"
        :indeterminate="indeterminate"
        @change="onCheckAllChange"
      >
        全选
      </Checkbox>
    </div>
    <div>
      <redo-outlined class="cursor-pointer" @click="handleClickKey" title="刷新" />
    </div>
  </div>
  <Divider v-if="plainOptions.length" style="margin: 10px; width: 100%" />
  <CheckboxGroup
    v-model:value="checkedList"
    :options="plainOptions"
    style="display: flex; flex-direction: column"
  />
</template>
<script lang="ts">
  import { defineComponent, reactive, toRefs, watch, ref } from 'vue';
  import { Checkbox, Divider } from 'ant-design-vue';
  import { RedoOutlined } from '@ant-design/icons-vue';
  export default defineComponent({
    components: { Checkbox, CheckboxGroup: Checkbox.Group, Divider, RedoOutlined },
    props: {
      list: {
        type: Array,
        defalut: () => [],
      },
      modelValue: {
        type: String,
        defalut: '',
      },
    },
    emits: ['change', 'handleClickKey', 'update:modelValue'],
    setup(props, { emit }) {
      const plainOptions = ref<Recordable[]>([]);
      const state = reactive({
        indeterminate: false,
        checkAll: false,
        checkedList: [],
      });

      const onCheckAllChange = (e: any) => {
        Object.assign(state, {
          checkedList: e.target.checked ? plainOptions.value.map((item) => item.value) : [],
          indeterminate: false,
        });
      };
      watch(
        () => state.checkedList,
        (val) => {
          state.indeterminate = !!val.length && val.length < plainOptions.value.length;
          state.checkAll =
            val.length === plainOptions.value.length && plainOptions.value.length != 0;
          console.log('checkedList-', val);
          emit('update:modelValue', val.join(','));
          emit('change', val);
        },
      );

      watch(
        () => props.list,
        (val) => {
          if (val && val.length) {
            plainOptions.value = val;
            Object.assign(state, {
              checkedList: plainOptions.value.map((item) => item.value),
            });
          } else {
            plainOptions.value = [];
          }
        },
      );

      const getCheckedList = () => {
        return state.checkedList;
      };
      const handleClickKey = () => {
        emit('handleClickKey');
      };

      return {
        ...toRefs(state),
        plainOptions,
        onCheckAllChange,
        getCheckedList,
        handleClickKey,
      };
    },
  });
</script>
